package uk.co.cocking.getinline2.pipeline.transformers;

import java.util.ArrayList;
import java.util.List;

import uk.co.cocking.getinline2.exceptions.EnvironmentException;
import uk.co.cocking.getinline2.pipeline.io.CouldNotProcessRecordException;

public class TransformerComposer<IncomingType> extends
		AbstractTransformer<IncomingType, IncomingType> {

	private final Transformer<IncomingType, IncomingType>[] transformers;

	public TransformerComposer(Transformer<IncomingType, IncomingType>... transformers) {
		this.transformers = transformers;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<IncomingType> transform(IncomingType incomingItem)
			throws CouldNotProcessRecordException {
		List<IncomingType> currentValues = enlist(incomingItem);
		for (Transformer<IncomingType, IncomingType> transformer: transformers) {
			List<IncomingType> transformedValues = new ArrayList<IncomingType>();
			for (IncomingType currentValue : currentValues) {
				transformedValues.addAll(transformer.transform(currentValue));
			}
			currentValues = transformedValues;
		}
		return currentValues;
	}

	@Override
	public List<IncomingType> open() throws EnvironmentException {
		List<IncomingType> result = super.open();
		for (Transformer<IncomingType, IncomingType> transformer: transformers) {
			result.addAll(transformer.open());
		}
		return result;
	}
	
	@Override
	public List<IncomingType> close() throws EnvironmentException {
		List<IncomingType> result = super.close();
		for (Transformer<IncomingType, IncomingType> transformer: transformers) {
			result.addAll(transformer.close());
		}
		return result;
	}

}
